<!--
 * @Author: chenzechao
 * @Date: 2024-02-04 09:19:50
 * @LastEditors: chenzechao
 * @LastEditTime: 2024-02-04 15:42:53
 * @FilePath: \accesscontrolui\src\views\xtpz\attendance-group\components\details.vue
 * @Description:
-->
<template>
  <div class="h-100">
    <div v-if="editOrgFlag" class="back-page m-b-16" @click="handleBackSbgl">
      <i class="icon icon icon-angle-left-circle-s"></i>
      返回
    </div>
    <br>
    <div class="page-container" style="border: 0px solid red;height: calc(100% - 55px);overflow-y: scroll;overflow-x: hidden">
      <div class="wrapperform m-b-16">
        <div class="searchbox">
          <el-form :inline="true" id="topInfo" inline :rules="rules" :model="form" ref="form">
            <el-form-item label="考勤组名称" prop="name">
              <el-input :title="form.name" v-model="form.name" placeholder="请输入" maxlength="24"
                        show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="应用人员">

              <el-popover
                  @show="popoverShow"
                  placement="bottom"
                  width="300"

                  trigger="click">
                <el-alert
                    v-if="handleType == 'add'"
                    :closable="false"
                    title="只显示没有考勤组的人员"
                    type="warning">
                </el-alert>
                <br>
                <vl-tree  element-loading-background="rgba(255,255,255,.6)" v-loading="treeLoading" id="customTree" empty-text="暂无数据" node-key="id"
                          :default-expanded-keys="defaultExpandedArr"
                          @check="Checks"
                          @node-click="nodeClick"
                          @current-change="currentChange"
                          @check-change="checkChange"
                          :filter-method="filterNode" ref="orgInfoTree" class="orgTree" show-checkbox
                          :height="400" :props="deprops" :data="noDepartmentPersonnel">

                  <div class="custom-tree-node" slot-scope="{ node, data }">
                       <span>
                           <i v-if="data.sex==undefined&&data.id!=-200" class="orgIcon iconfont-KUI icon-modules"></i>
                           <i v-if="data.sex!==undefined" :class="{'female':data.sex==1}"
                              class="el-icon-user-solid userIcon" style="margin-right:5px;">
                           </i>
                           <span style="width: 120px;display: inline-block;vertical-align: bottom" class="ellipsis"
                                 :title="node.label">{{ node.label }}</span>
                        </span>
                  </div>
                </vl-tree>
                <el-input readonly slot="reference" v-model="personnelCount" placeholder=""></el-input>
              </el-popover>
            </el-form-item>





            <el-form-item class="BlankPlaceholder" label="." style="float: right">
              <!--保存-->
              <el-button size="small" type="primary" :loading="saveLoading" @click="onSubmit">{{this.i18n.t('save')}}
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="wrapperform m-b-16">
        <header class="has-checkout">
          <span>考勤类型</span>
        </header>
        <div class="search2box">
          <el-form :inline="true" :rules="rules" :model="form" ref="form2">
            <el-row  type="flex" justify="space-between" :gutter="20">
              <el-col :span="3" style="margin-right: 10px">
                <el-form-item label="" class="lowLayout" prop="type">
                  <el-radio-group v-model="form.type" @change="handleChange">
                    <el-radio v-if="form.type==0 || this.classType == 0" :label="0">固定班制</el-radio>
                    <el-radio v-if="form.type==1 || this.classType == 0" :label="1">排班制</el-radio>
                    <el-radio v-if="form.type==2 || this.classType == 0" :label="2">自由班制</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="21">
                <el-form-item class="alertText">
                  <el-alert
                      show-icon
                      v-if="form.type==0 || this.classType == 0"
                      title="固定班制：应用于每天上班时间都固定不变的。例如：双休的考勤方式即周一~周五，08:30-18:00;单休周一~周六，08:30-18:00;大小周的考勤方式，即一周工作6天一周工作5天，单双休交替循环"
                      type="warning">
                  </el-alert>
                  <el-alert
                      show-icon
                      v-if="form.type==1 || this.classType == 0"
                      title="排班制：有多种形式，包括固定班制、三班两倒、四班三倒等。根据企业或组织的需要，可以选择适合的排班方式。例如，对于需要24小时服务的行业，可以采用三班两倒或四班三倒的方式，将一天的工作时间分为两个或三个班次，每个班次工作一段时间后休息一段时间，循环进行。"
                      type="warning">
                  </el-alert>
                  <el-alert
                      show-icon
                      v-if="form.type==2 || this.classType == 0"
                      title="自由班制：没有具体的班次，考勤组人员可以在打卡时段内自由打卡，按照打卡时段统计上班时长。"
                      type="warning">
                  </el-alert>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <el-row :gutter="20">
        <el-col :span="24">
          <!--        固定班制-->
          <RegularClasses ref="RegularClasses" @getParams="getParams"
                          :detailRow="detailRow"
                          :attendanceGroupId="attendanceGroupId"
                          :handleTypeSub="handleType"
                          v-if="form.type == 0" />
          <!--        排班制-->
          <FreeClasses ref="FreeClasses" :getNameByIdFn="getNameById" @getParams="getParams"
                       :filterPersonList="filterPersonList"
                       :classesList="classesList"
                       :detailRow="detailRow" :personnelList="personnelList" :handleTypeSub="handleType" v-if="form.type == 1" />
          <!--        自由班制表单-->
          <ArrangeClasses ref="ArrangeClasses" @getParams="getParams" :detailRow="detailRow" :handleTypeSub="handleType" v-if="form.type == 2" />
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import Panel from "@/components/panel.vue";
import Pagination from "@/components/Pagination/index.vue";
import RegularClasses from './regular-classes.vue'
import ArrangeClasses from './arrange-classes.vue'
import FreeClasses from './free-classes.vue'
import {getdepartmenttree} from "@/api/pcmj/zzxx";
import {filterTreeData} from "@/views/rygl/utils";
import {
  attendancegroupCreate,
  attendancegroupGetdetails,
  attendancegroupUpdate
} from "@/api/pcmj/kqz";
import {workingscheduleGetlist} from "@/api/pcmj/bcgl";
export default {
  components: {Panel, Pagination,RegularClasses,ArrangeClasses,FreeClasses },
  data() {
    var validateName = (rule, value, callback) => {
      if (value === '') {
        // 请输入班次名称
        callback(new Error('请输入考勤组名称'));
      } else {
        callback();
      }
    };
    var validateAera = (rule, value, callback) => {
      if (value === null) {
        // 请输入班次名称
        callback(new Error('请选择应用范围'));
      } else {
        callback();
      }
    };
    return {
      personnelCount:"0人",
      filterPersonList:[],
      classType: 0,
      rules: {
        name: [
          {validator: validateName, required: true, trigger: 'blur'},
          {max: 24, message: '长度最大 24 个字符', trigger: 'blur' }
        ],
        aera:[
          {validator: validateAera, required: true, trigger: 'blur'}
        ]
      },
      defaultExpandedArr: [],
      treeLoading: false,
      form: {
        name: "",
        aera:null,
      },
      title: '',
      noDepartmentPersonnel: [],
      deprops: { // 默认配置
        value: 'id', // treeId 为节点id，唯一值
        label: 'name',
        children: 'children'
      },
      attendanceGroupId:null,
      childrenParams:null,
      saveLoading:false,
      detailRow:{},
      personnelList:null,
      classesList:[]
    };
  },
  watch:{
    "form.aera"(newVal,oldVal){
      if (newVal===0){
        this.setTreeSelection([this.noDepartmentPersonnel[0].id])
        // this.defaultExpandedArr=[this.noDepartmentPersonnel[0].id]
      }else{
        this.setTreeSelection([])
      }
    }
  },
  props: {
    handleType:{
      type:String,
      default:"add"
    },
    editOrgFlag: {
      type: Boolean,
      default: false
    },
    tableRow:{
      type:Object,
      default:()=>{
        return {}
      }
    }
  },
  methods:{
    visibleChange(state){
      console.log(state);
    },
    handleChange() {
      this.personnelCount="0人"
      this.setTreeSelection([])
      this.$forceUpdate()
    },
    checkChange(data, checked, node){
      console.log('checked',checked);
      // console.log('checkChange',data, checked, node);
      this.personnelList=this.getOrginfoCheckedKeys()
      this.personnelCount=this.personnelList.length+"人"
      console.log(243, this.personnelList);
      this.getOrgPersionCount2(this.noDepartmentPersonnel[0].children)

    },
    Checks(row,node){
      console.log(row, node);
    },
    currentChange(row,node){
      // console.log(row, node);
    },
    nodeClick(node, data){
      // console.log('nodeClick',row, node, e);
    },
    // 获取组织树下选中的人员
    getOrginfoCheckedKeys(){

      // this.$parent.handleType="add"//模拟添加环境，功能开发完后必须删除

      var checkedKeys=this.$refs.orgInfoTree.getCheckedNodes()
      console.log('this.$refs.orgInfoTree',this.$refs.orgInfoTree,checkedKeys);
      // return
      // debugger
      var result=[]
      if(checkedKeys.length){

        checkedKeys.map(item=>{
          if(item.sex!==undefined){
            var temp={
              id:item.id,
              // name:this.getNameById(item.id)//人员名称
            }
            // if (this.form.type == 1&&this.handleType=="add"){
            //   temp.name=item.name
            // }
            result.push(temp)
          }
        })
        console.log('人员列表', result);
        return result
      }else{
        console.log('人员列表', result);
        return result
      }
    },
    getParams(data){
      this.childrenParams=data
      // if (this.form.type===2){
      //
      // }
    },
    aeraChange(val){

    },
    resetSearch(){
      console.log('resetSearch');
      console.log(this.$refs.form.resetFields());
    },
    updateParentPage(){
      // 更新父页面表格
      this.$parent.reset()
      this.$parent.editOrgFlag=false
    },
    // 更新考勤组
    attendancegroupUpdate(params){
      attendancegroupUpdate(params).then(res=>{
        if (res.code == 200) {
          // 操作成功
          this.W.$tips("success", this.i18n.t('Operation successful'));
          this.updateParentPage()
        }
      }).catch().finally(()=>{
        this.saveLoading=false
      })
    },


    // 获取班次列表
    workingscheduleGetlist(){
      workingscheduleGetlist({
        pageNumber:1,
        pageSize:999,
        name:null
      }).then(res=>{
        if (res.code == 200) {

          res.data.values.forEach((item,index) => {
            if(index%3==0) {
              item.color="background: #ffe9d1;"
            } else if(index%3==1) {
              item.color="background: #fffad1;"
            } else {
              item.color="background: #e8e5fb;"
            }
          });
          this.classesList=[
            {
              label:'快捷选项',
              options:[
                {
                  name:"休息",
                  id:-100,
                  color: "background: #cff2bf;"
                }
              ]
            },
            {
              label: '班次列表',
              options:res.data.values
            }
          ]

          if (this.handleType=="add"){
            this.form.type=0
            this.classType=0
          }
          if (this.handleType=="edit"){
            this.attendanceGroupId=this.tableRow.id
            this.classType=1

            // 考勤组名称
            this.form.name=this.tableRow.name
            if (this.form.type==1){

            }else{

            }
            // 查询此班次的详细信息
            this.attendancegroupGetdetails(this.tableRow.id)
          }

        }
      }).catch().finally(()=>{

      })
    },
    // 人员列表显示时
    popoverShow(){
      // 编辑时，设置选中的人员
      // debugger
      // if (this.handleType == 'edit'&&this.tableRow.personnelInfos.length){
      //   var defaultCheckedKeys=[]
      //   console.log(537);
      //   this.tableRow.personnelInfos.map(item=>{
      //     defaultCheckedKeys.push(item.id)
      //   })
      //   console.log('设置选中的数据',defaultCheckedKeys);
      //   this.setTreeSelection(defaultCheckedKeys)
      // }
    },
    // 获取考勤组详情
    attendancegroupGetdetails(id){
      attendancegroupGetdetails(id).then(res=>{
        if (res.code == 200) {
          this.detailRow=res.data
          this.form.type=this.tableRow.type
          console.log(333,this.detailRow);
          this.detailRow=res.data
          this.tableRow.personnelInfos=res.data.personnelInfos
          var defaultCheckedKeys=[]
          this.tableRow.personnelInfos.map(item=>{
            defaultCheckedKeys.push(item.id)
          })
          console.log('设置选中的数据',defaultCheckedKeys);
          this.setTreeSelection(defaultCheckedKeys)

          this.personnelCount=this.tableRow.personnelInfos.length+"人"
        }
      }).catch(()=>{
        this.W.$tips("warning", "考勤组数据加载失败");
      }).finally(()=>{
        // this.saveLoading=false
      })
    },
    // 创建考勤组
    attendancegroupCreate(params){
      attendancegroupCreate(params).then(res=>{
        if (res.code == 200) {
          // 添加成功
          this.W.$tips("success", this.i18n.t('Add successfully!'));
          this.updateParentPage()
        }
      }).catch().finally(()=>{
        this.saveLoading=false
      })
    },
    onSubmit(){
      var persionList=this.getOrginfoCheckedKeys()
      console.log('保存人员列表',persionList);

      // if (!persionList.length){
      //   this.W.$tips("warning", "请在右侧人员列表选择对应的人员");
      //   return
      // }
      if (this.form.type===0){
        // 触发固定班制表单校验
        this.$refs.RegularClasses.childrenGetParams()
      }
      if (this.form.type===1){
        // 触发排班制表单校验
        this.$refs.FreeClasses.childrenGetParams()
      }
      if (this.form.type===2){
        // 触发自由班制表单校验
        this.$refs.ArrangeClasses.childrenGetParams()
      }



      console.log('内部表单校验结果：',this.childrenParams);
      this.$refs.form.validate((valid) => {
        // console.log('外部表单校验结果：',valid);
        if (valid&&this.childrenParams){
          this.saveLoading=true
          var params=Object.assign(this.childrenParams,this.form)
          params.personnelInfos=persionList
          delete params.aera
          if (this.handleType=="add"){
            params.creatorId=JSON.parse(localStorage.getItem("userInfo")).userId
          }else{
            params.creatorId=this.tableRow.creatorId
            params.id=this.tableRow.id
          }

          if (this.form.type===0){
             params.g_SpecialDays = this.$refs.RegularClasses.allSpecialDays.values;
          }
          if (this.handleType=="add"){
            this.attendancegroupCreate(params)
          }else{
            this.attendancegroupUpdate(params)
          }

          console.log('最终的JSON',params);

        } else {
          console.log('有验正未通过');
          return false;
        }
      })
    },
    filterNode() {

    },
    // 获取组织下的人数
    getOrgPersionCount2(item) {
      let count = 0
      item.forEach(i => {
        if (i.children?.length > 0) {
          count += this.getOrgPersionCount(i.children)
        }
      })

      // console.log('1111', count)
      return count
    },
    // 获取组织下的人数
    getOrgPersionCount(item) {
      if (!this.personnelList || this.personnelList.length === 0) return 0
      var count = 0
      if (Array.isArray(item)) {
        item.map(res => {
          if (res.sex !== undefined && this.personnelList.find(list => list.id === res.id)) {
            count++
          }
        })
      }

      return count
    },
    // 根据人员ID返回此人员的name
    getNameById(id){
      const stack = [...this.noDepartmentPersonnel]; // 使用堆栈模拟迭代
      while (stack.length > 0) {
        const item = stack.pop();
        if (item.id === id) {
          return item.name;
        }
        if (item.children) {
          stack.push(...item.children);
        }
      }
      return null;
    },
    /**
     * @description  获取部门人员树
     * @param :
     **/
    getdepartmenttree() {
      this.treeLoading=true
      var allPersonnel=[
        {
          id: -200,
          name: this.i18n.t('All'),
          children: [
            {
              id: -100,
              name: this.i18n.t('default'),
              children: []
            }
          ]
        }
      ]

      var params={
        IncludePersonInfo: true,
        NoAttandanceGroup:true
      }
      if (this.handleType == 'edit'){
        params.attandanceId=this.tableRow.id
      }
      let self = this;
      getdepartmenttree(params).then((res) => {
        if (res.code === 200) {
          // 有组织的人员
          if (res.data.rootDepartments.length) {
            res.data.rootDepartments = filterTreeData(res.data.rootDepartments)
            // 全部分类下，push组织列表
            res.data.rootDepartments.map(item => {
              allPersonnel[0].children.push(item)
            })

          }
          // 无组织的人员
          if (res.data.personnelOfWithOutDepartment.length) {
            // 把无组织的人员，合并到默认分类下
            allPersonnel[0].children[0].children=res.data.personnelOfWithOutDepartment
          }
          this.noDepartmentPersonnel=allPersonnel

          this.filterPersonList=this.filterPerson(this.noDepartmentPersonnel)
          // console.log('人员树的JSON',JSON.stringify(this.noDepartmentPersonnel));
          console.log('构建后的人员列表',this.filterPersonList);
          // debugger
          // 默认展开顶级节点
          this.defaultExpandedArr=[this.noDepartmentPersonnel[0].id]

          // 获取班次列表
          this.workingscheduleGetlist()


        }
      }).catch().finally(() => {
        setTimeout(()=>{
          this.treeLoading=false
        },600)
      })

    },
    // 根据人员JSON树，构建人员列表
    filterPerson(json){

      var result=[]
      function filterRecursive(data){
        for (var i=0;i<data.length;i++){
          var temp={
            sex:null,
            name:null,
            personnelId:null
          }
          if ('sex' in data[i]){
            temp.sex=data[i].sex
            temp.name=data[i].name
            temp.personnelId=data[i].id
            result.push(temp)
          }
          if (data[i].children){
            filterRecursive(data[i].children)
          }
        }
      }
      filterRecursive(json)
      return result
    },
    // 设置树选中
    setTreeSelection(data){
      this.$refs.orgInfoTree.setCheckedKeys(data)
    },
    /**
     * @description  返回上个界面
     * @return not
     * @author qiankui 2024-2-26 11:46:45
     **/
    handleBackSbgl() {
      this.$parent.editOrgFlag=false
      // // 更新父页面的数据
      // this.updateParentData()
      // // 重置vuex证件号码、姓名、照片、性别、NFC卡号
      // this.resetStoreState()
    },
  },
  mounted(){
    // 获取人员列表组织树
    this.getdepartmenttree()



  }
};
</script>
<style lang="scss" scoped>
  //::v-deep .group-radio {
  //  flex-direction: column;
  //}

  .search2box .el-form-item__content .el-radio {
    padding: 10px 0;
    margin-bottom: 20px;
  }

  .search2box .el-alert--warning.is-light {
    background: #e1eefc;
    margin: 15px 0;
  }

  .search2box .el-alert--warning.is-light label {
    width: 1450px;
    background: #e1eefc;
  }

  .search2box .el-alert.is-light .el-alert__closebtn {
    display: none;
  }

  .search2box .el-alert__title {
    color: #4f93e0;
    line-height: 16px;

  }
  .lowLayout label {
    display: block;
    margin-top: 25px;
  }
  ::v-deep .alertText .el-alert__title,::v-deep .alertText .el-icon-warning {
    color: #4f93e0;
    display: inline-block;
    line-height: 20px;
  }
  ::v-deep .el-alert.is-light .el-alert__closebtn {
    display: none !important;
  }
  #customTree {
    /*border: 1px solid red;*/
    /*height: calc(100% - 90px);*/
    overflow-y: scroll !important;
    .userIcon,.orgIcon{
      color:#0666d2;
      &.female{
          color:#ff7700;
      }
    }
    .orgIcon{
        margin-right: 5px;
    }
    .treeTool{

      .treeToolIcon{
          color: #409eff;
          /*font-weight: bold;*/
          margin-left: 8px;
          vertical-align: middle;
      }
    }
  }
  ::v-deep .el-select-dropdown__wrap{
    //max-height: 700px !important;
  }
  //::v-deep .el-popover.el-popper{
  //  left: 700px;
  //}
  .ellipsis{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>

<style scoped lang="scss">
@import '../index.scss';
</style>
